pub mod banner;
pub mod member;
pub mod menu;
pub mod role;
pub mod title;
pub mod types;
pub mod user;

pub use banner::*;
pub use member::*;
pub use menu::*;
use rbatis::rbdc::{db::ExecResult, Error};
pub use role::*;
use serde::Serialize;
use std::fmt::Debug;
pub use title::*;
pub use types::*;
pub use user::*;

// 统一返回vo
#[derive(Serialize, Debug, Clone)]
pub struct ApiResult<T>
where
    T: Serialize + Debug,
{
    pub code: i32,
    pub msg: String,
    pub data: Option<T>,
}

impl<T: Serialize + Debug> hypers::prelude::Responder for ApiResult<T> {
    fn response(self, mut builder: hypers::prelude::Response) -> hypers::prelude::Response {
        builder.json(&self);
        builder
    }
}

// 处理统一返回
pub fn handle_result(result: Result<ExecResult, Error>) -> ApiResult<String> {
    match result {
        Ok(_u) => ok_result(),
        Err(err) => err_result_msg(err.to_string()),
    }
}

pub fn ok_result() -> ApiResult<String> {
    ApiResult {
        msg: "操作成功".to_owned(),
        code: 0,
        data: Some("None".to_owned()),
    }
}

pub fn ok_result_msg(msg: impl Into<String>) -> ApiResult<String> {
    ApiResult {
        msg: msg.into(),
        code: 0,
        data: Some("None".to_owned()),
    }
}

pub fn ok_result_data<T: Serialize + Debug>(data: T) -> ApiResult<T> {
    ApiResult {
        msg: "操作成功".to_owned(),
        code: 0,
        data: Some(data),
    }
}

pub fn err_result_msg(msg: impl Into<String>) -> ApiResult<String> {
    ApiResult {
        msg: msg.into(),
        code: 1,
        data: Some("None".to_owned()),
    }
}

// 统一返回分页
#[derive(Serialize, Debug, Clone)]
pub struct ResponsePage<T>
where
    T: Serialize + Debug,
{
    pub code: i32,
    pub msg: String,
    pub total: u64,
    pub success: bool,
    pub data: Option<T>,
}

pub fn ok_result_page<T: Serialize + Debug>(data: T, total: u64) -> ResponsePage<T> {
    ResponsePage {
        msg: "操作成功".to_owned(),
        code: 0,
        success: true,
        data: Some(data),
        total,
    }
}

pub fn err_result_page(msg: impl Into<String>) -> ResponsePage<String> {
    ResponsePage {
        msg: msg.into(),
        code: 1,
        success: false,
        data: Some("None".to_owned()),
        total: 0,
    }
}
